package com.fileupload.process.strategy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 文件完成操作策略工厂
 * 负责创建和管理不同的文件操作策略实例
 * @author 小乙
 */
@Component
public class FileFinishActionStrategyFactory {
    
    private static final Logger logger = LoggerFactory.getLogger(FileFinishActionStrategyFactory.class);
    
    // 策略缓存，避免重复创建实例
    private final Map<String, FileFinishActionStrategy> strategyCache = new ConcurrentHashMap<>();
    
    /**
     * 根据策略名称获取策略实例
     * 
     * @param strategyName 策略名称
     * @param monitorDir 监控目录（用于相对路径策略）
     * @return 文件操作策略实例，如果未找到对应策略则返回默认策略（保留策略）
     */
    public FileFinishActionStrategy getStrategy(String strategyName, String monitorDir) {
        if (strategyName == null || strategyName.trim().isEmpty()) {
            logger.warn("Strategy name is empty, using default 'keep' strategy");
            return getDefaultStrategy();
        }
        
        // 从缓存获取策略
        return strategyCache.computeIfAbsent(strategyName.trim().toLowerCase(), name -> {
            logger.debug("Creating strategy for name: {}", name);
            
            // 根据策略名称创建对应的策略实例
            switch (name) {
                case "delete":
                    return new DeleteFileStrategy();
                case "keep":
                    return new KeepFileStrategy();
                case "same-move":
                    return new SameMoveFileStrategy();
                case "time-based":
                    return new TimeBasedMoveFileStrategy();
                case "relative-path":
                    return new RelativePathMoveFileStrategy(monitorDir);
                case "diff-move":
                    return new DiffMoveFileStrategy();
                case "diff-move-time":
                    return new DiffMoveTimeFileStrategy();
                case "diff-move-path":
                    return new DiffMovePathFileStrategy(monitorDir);
                default:
                    logger.warn("Unknown strategy: {}, using default 'keep' strategy", name);
                    return getDefaultStrategy();
            }
        });
    }
    
    /**
     * 获取默认策略（保留策略）
     * 
     * @return 默认策略实例
     */
    private FileFinishActionStrategy getDefaultStrategy() {
        return strategyCache.computeIfAbsent("keep", KeepFileStrategy::new);
    }
    
    /**
     * 清除策略缓存
     * 用于测试或需要重新加载策略的场景
     */
    public void clearCache() {
        strategyCache.clear();
        logger.debug("Strategy cache cleared");
    }
}
